import { saveReceipt } from '@/services/api/api-pressconference';
import { PlusOutlined, SendOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  EditableProTable,
  ProColumns,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Button, message } from 'antd';
import { useRef, useState } from 'react';
import { useAccess, useModel } from 'umi';

interface AddReceiptProps {
  recordId: string | undefined;
  onSave: () => void;
}

const AddReceipt: React.FC<AddReceiptProps> = ({ recordId, onSave }) => {
  const { initialState } = useModel('@@initialState');
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();

  const actionRef = useRef<ActionType>();

  const [dataSource, setDataSource] = useState<any>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const columns: ProColumns<PressconferenceData.ReceiptParticipatePage>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          姓名
        </span>
      ),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          电话
        </span>
      ),
      dataIndex: 'phone',
      align: 'center',
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          描述
        </span>
      ),
      dataIndex: 'describes',
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <DrawerForm
      title="填写回复"
      trigger={
        <Button
          icon={<SendOutlined />}
          type="primary"
          style={{
            background: '#87d068',
          }}
        >
          回复
        </Button>
      }
      layout="horizontal"
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: 800,
      }}
      initialValues={{
        assignType: '4',
      }}
      onFinish={async (values) => {
        if (
          values.content === undefined ||
          values.content.length === 0 ||
          values.content.trim() === ''
        ) {
          message.warning('请输入回执内容');
          return;
        }

        if (editableKeys.length > 0) {
          message.warning('请保存参会人员名单');
          return;
        }

        if (dataSource.length == 0) {
          message.warning('请添加参会人员信息');
          return;
        }

        const response = await saveReceipt({ recordId, ...values, participates: dataSource });
        if (response.code === 0) {
          message.success('提交成功');
          onSave();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProFormTextArea
        name="content"
        required
        label=""
        placeholder="请输入回执"
        fieldProps={{
          rows: 10,
          count: {
            show: true,
          },
        }}
      />
      <EditableProTable<PressconferenceData.ReceiptParticipatePage>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        dateFormatter="id"
        defaultSize={'small'}
        pagination={false}
        search={false}
        options={false}
        ghost
        headerTitle={
          <Alert
            message="参会人员"
            type="info"
            showIcon
            style={{
              fontSize: 12,
            }}
          />
        }
        dataSource={dataSource}
        onChange={setDataSource}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              actionRef.current?.addEditRecord({
                id: (Math.random() * 1000000).toFixed(0),
                name: '',
              });
            }}
            type="primary"
          >
            添加参会人员
          </Button>,
        ]}
        recordCreatorProps={false}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDom) => {
            return [defaultDom.save, defaultDom.cancel];
          },
          onChange: setEditableRowKeys,
        }}
      />
    </DrawerForm>
  );
};

export default AddReceipt;
